package org.JDBC;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DDLTest {
    //数据库连接四要素
    private String driverClass = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://127.0.0.1:3306/briup";
    private String user = "root";
    private String password = "1234";
    
    //删除表
    @Test
    public void dropTable() {
        Statement stmt = null;
        Connection conn = null;
        try {
            //1.加载注册驱动
            Class.forName(driverClass);
            //2.获取连接对象
            conn = DriverManager.getConnection(url,user,password);
            //3.获取Statement对象
            stmt = conn.createStatement();
            //4.执行SQL语句
            String sql = "drop table if exists t_user";
            int rows = stmt.executeUpdate(sql);
            //5.处理结果
            System.out.println("返回结果 rows: " + rows);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if(stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            // 添加连接关闭
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //创建表
    @Test
    public void createTable() {
        Statement stmt = null;
        Connection conn = null;
        try {
            //1.加载注册驱动
            Class.forName(driverClass);
            //2.获取连接对象
            conn = DriverManager.getConnection(url, user, password);
            //3.获取Statement对象
            stmt = conn.createStatement();
            //4.执行SQL语句
            String sql = "create table t_user("
                    + "id bigint primary key,"  // 使用bigint更适合id
                    + "name varchar(50) not null,"
                    + "age int"
                    + ")";
            int rows = stmt.executeUpdate(sql);
            //5.处理结果
            System.out.println("运行结果 rows: " + rows);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            // 添加连接关闭
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    // 添加测试方法调用
    public static void main(String[] args) {
        DDLTest test = new DDLTest();
        test.dropTable();
        test.createTable();
    }
}